// 性能优化工具

/**
 * 性能监控类
 */
class PerformanceMonitor {
  constructor() {
    this.metrics = {}
    this.observers = []
    this.init()
  }

  init() {
    // 监听页面加载性能
    this.observePageLoad()
    // 监听资源加载性能
    this.observeResourceTiming()
    // 监听长任务
    this.observeLongTasks()
    // 监听布局偏移
    this.observeLayoutShift()
    // 监听首次输入延迟
    this.observeFirstInput()
  }

  /**
   * 监听页面加载性能
   */
  observePageLoad() {
    window.addEventListener('load', () => {
      setTimeout(() => {
        const navigation = performance.getEntriesByType('navigation')[0]
        if (navigation) {
          this.metrics.pageLoad = {
            // DNS查询时间
            dnsTime: navigation.domainLookupEnd - navigation.domainLookupStart,
            // TCP连接时间
            tcpTime: navigation.connectEnd - navigation.connectStart,
            // 请求响应时间
            responseTime: navigation.responseEnd - navigation.requestStart,
            // DOM解析时间
            domParseTime: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
            // 页面完全加载时间
            loadTime: navigation.loadEventEnd - navigation.loadEventStart,
            // 总加载时间
            totalTime: navigation.loadEventEnd - navigation.fetchStart
          }
          
          console.log('📊 页面加载性能:', this.metrics.pageLoad)
          this.reportMetrics('pageLoad', this.metrics.pageLoad)
        }
      }, 0)
    })
  }

  /**
   * 监听资源加载性能
   */
  observeResourceTiming() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        const entries = list.getEntries()
        entries.forEach(entry => {
          if (entry.initiatorType === 'img' || entry.initiatorType === 'script' || entry.initiatorType === 'css') {
            const resourceTime = {
              name: entry.name,
              type: entry.initiatorType,
              duration: entry.duration,
              size: entry.transferSize || 0
            }
            
            // 记录慢资源
            if (entry.duration > 1000) {
              console.warn('🐌 慢资源加载:', resourceTime)
            }
          }
        })
      })
      
      observer.observe({ entryTypes: ['resource'] })
    }
  }

  /**
   * 监听长任务
   */
  observeLongTasks() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        const entries = list.getEntries()
        entries.forEach(entry => {
          console.warn('⏱️ 长任务检测:', {
            duration: entry.duration,
            startTime: entry.startTime,
            name: entry.name
          })
        })
      })
      
      observer.observe({ entryTypes: ['longtask'] })
    }
  }

  /**
   * 监听布局偏移
   */
  observeLayoutShift() {
    if ('PerformanceObserver' in window) {
      let clsValue = 0
      const observer = new PerformanceObserver((list) => {
        const entries = list.getEntries()
        entries.forEach(entry => {
          if (!entry.hadRecentInput) {
            clsValue += entry.value
          }
        })
        
        if (clsValue > 0.1) {
          console.warn('📐 布局偏移过大:', clsValue)
        }
      })
      
      observer.observe({ entryTypes: ['layout-shift'] })
    }
  }

  /**
   * 监听首次输入延迟
   */
  observeFirstInput() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        const entries = list.getEntries()
        entries.forEach(entry => {
          const fid = entry.processingStart - entry.startTime
          console.log('👆 首次输入延迟:', fid + 'ms')
          
          if (fid > 100) {
            console.warn('⚠️ 首次输入延迟过高:', fid + 'ms')
          }
        })
      })
      
      observer.observe({ entryTypes: ['first-input'] })
    }
  }

  /**
   * 报告性能指标
   */
  reportMetrics(type, data) {
    // 这里可以发送数据到分析服务
    if (window.gtag) {
      window.gtag('event', 'performance_metric', {
        metric_type: type,
        metric_data: data
      })
    }
  }

  /**
   * 获取性能指标
   */
  getMetrics() {
    return this.metrics
  }
}

/**
 * 图片懒加载
 */
export function lazyLoadImages() {
  const images = document.querySelectorAll('img[data-src]')
  
  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target
        img.src = img.dataset.src
        img.removeAttribute('data-src')
        observer.unobserve(img)
      }
    })
  })
  
  images.forEach(img => imageObserver.observe(img))
}

/**
 * 防抖函数
 */
export function debounce(func, wait, immediate = false) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func(...args)
  }
}

/**
 * 节流函数
 */
export function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 预加载资源
 */
export function preloadResource(url, type = 'image') {
  return new Promise((resolve, reject) => {
    if (type === 'image') {
      const img = new Image()
      img.onload = () => resolve(img)
      img.onerror = reject
      img.src = url
    } else if (type === 'script') {
      const script = document.createElement('script')
      script.onload = () => resolve(script)
      script.onerror = reject
      script.src = url
      document.head.appendChild(script)
    } else if (type === 'css') {
      const link = document.createElement('link')
      link.onload = () => resolve(link)
      link.onerror = reject
      link.rel = 'stylesheet'
      link.href = url
      document.head.appendChild(link)
    }
  })
}

/**
 * 缓存管理
 */
export class CacheManager {
  constructor() {
    this.cache = new Map()
    this.maxSize = 100
  }

  set(key, value, ttl = 60000) {
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value
      this.cache.delete(firstKey)
    }
    
    this.cache.set(key, {
      value,
      timestamp: Date.now(),
      ttl
    })
  }

  get(key) {
    const item = this.cache.get(key)
    if (!item) return null
    
    if (Date.now() - item.timestamp > item.ttl) {
      this.cache.delete(key)
      return null
    }
    
    return item.value
  }

  clear() {
    this.cache.clear()
  }

  size() {
    return this.cache.size
  }
}

/**
 * 内存使用监控
 */
export function monitorMemoryUsage() {
  if ('memory' in performance) {
    setInterval(() => {
      const memory = performance.memory
      const usedMB = Math.round(memory.usedJSHeapSize / 1048576)
      const totalMB = Math.round(memory.totalJSHeapSize / 1048576)
      const limitMB = Math.round(memory.jsHeapSizeLimit / 1048576)
      
      console.log('💾 内存使用:', {
        used: usedMB + 'MB',
        total: totalMB + 'MB',
        limit: limitMB + 'MB',
        percentage: Math.round((usedMB / limitMB) * 100) + '%'
      })
      
      if (usedMB / limitMB > 0.8) {
        console.warn('⚠️ 内存使用率过高:', Math.round((usedMB / limitMB) * 100) + '%')
      }
    }, 10000) // 每10秒检查一次
  }
}

/**
 * 网络状态监控
 */
export function monitorNetworkStatus() {
  if ('connection' in navigator) {
    const connection = navigator.connection
    
    console.log('🌐 网络状态:', {
      effectiveType: connection.effectiveType,
      downlink: connection.downlink + 'Mbps',
      rtt: connection.rtt + 'ms',
      saveData: connection.saveData
    })
    
    connection.addEventListener('change', () => {
      console.log('📡 网络状态变化:', {
        effectiveType: connection.effectiveType,
        downlink: connection.downlink + 'Mbps'
      })
    })
  }
}

// 创建全局性能监控实例
export const performanceMonitor = new PerformanceMonitor()

// 创建全局缓存管理器
export const cacheManager = new CacheManager()

// 自动初始化
if (typeof window !== 'undefined') {
  // 启动内存监控
  monitorMemoryUsage()
  
  // 启动网络监控
  monitorNetworkStatus()
  
  // 初始化图片懒加载
  document.addEventListener('DOMContentLoaded', lazyLoadImages)
} 